package createThread.cn.tedu.threaddemo.test9;

class MyBlockingQueue{

    private int[] arr = new int[20];
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    private final Object lock = new Object();
    public void put(int n) throws InterruptedException {
        synchronized (MyBlockingQueue.class){
            while(size == arr.length){
                MyBlockingQueue.class.wait();
            }
            arr[tail] = n;
            tail++;
            if(tail == arr.length){
                tail = 0;
            }
            size++;
            MyBlockingQueue.class.notify();
        }

    }

    public int take() throws InterruptedException {


        synchronized (MyBlockingQueue.class){
            while(size == 0){
                MyBlockingQueue.class.wait();
            }
            int e = 0;
            e = arr[head];
            head++;
            if(head == arr.length){
                head = 0;
            }
            size--;
            MyBlockingQueue.class.notify();
            return e;
        }

    }

}
public class Demo2 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
        Thread t1= new Thread(()->{
            int n = 0;
            while (true){
                try {
                    myBlockingQueue.put(n);
                    System.out.println("myblockingqueue 添加的元素 : " + n);
                    n++;
//                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2 = new Thread(()->{
            while (true){
                try {
                    int e = myBlockingQueue.take();
                    System.out.println("myblockingqueue 获取的元素 : " + e);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
